const express = require("express");
const router = express.Router();
const db = require("../config/database");
const { authenticateToken } = require("../middleware/auth");
const { verifyIdentity } = require("../utils/identityVerification");
const path = require("path");
const fs = require("fs");
const WordProcessor = require("../utils/wordProcessor");

/**
 * @swagger
 * /api/contracts/dashboard:
 *   get:
 *     summary: 获取资金概览仪表板数据
 *     tags: [Contracts]
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: 获取成功
 *                 data:
 *                   type: object
 *                   properties:
 *                     fundOverview:
 *                       type: object
 *                       properties:
 *                         lentAmount:
 *                           type: number
 *                           description: 借出资金
 *                         borrowedAmount:
 *                           type: number
 *                           description: 借入资金
 *                         receivedAmount:
 *                           type: number
 *                           description: 已收金额
 *                         receivableAmount:
 *                           type: number
 *                           description: 待收金额
 *                         paidAmount:
 *                           type: number
 *                           description: 已还金额
 *                         payableAmount:
 *                           type: number
 *                           description: 待还金额
 *                     contractStats:
 *                       type: object
 *                       properties:
 *                         total:
 *                           type: integer
 *                           description: 全部合同数
 *                         pending:
 *                           type: integer
 *                           description: 待签署合同数
 *                         executing:
 *                           type: integer
 *                           description: 待履约合同数
 *                         overdue:
 *                           type: integer
 *                           description: 已逾期合同数
 *                         completed:
 *                           type: integer
 *                           description: 已还清合同数
 */
router.get("/dashboard", authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id; // 从JWT token中获取用户ID

    // 获取当前用户的详细信息，用于匹配参与的合同
    const [userRows] = await db.execute(
      "SELECT idCard, phone, realName FROM user WHERE id = ?",
      [userId]
    );
    const currentUser = userRows[0];

    // 构建查询条件，不仅查询用户创建的合同，还要查询用户参与的合同
    let whereClause = "WHERE status != -1 AND (user_id = ?";
    let params = [userId];

    // 添加用户参与的合同条件（作为借款人或出借人）
    if (
      currentUser &&
      (currentUser.idCard || currentUser.phone || currentUser.realName)
    ) {
      whereClause +=
        " OR (lender_name = ? OR lender_id_card = ? OR lender_phone = ?)";
      params.push(
        currentUser.realName || "",
        currentUser.idCard || "",
        currentUser.phone || ""
      );

      whereClause +=
        " OR (borrower_real_name = ? OR borrower_real_id_card = ? OR borrower_phone = ?)";
      params.push(
        currentUser.realName || "",
        currentUser.idCard || "",
        currentUser.phone || ""
      );
    }

    whereClause += ")";

    // 获取资金概览数据，根据用户在合同中的实际角色计算
    const [fundRows] = await db.execute(
      `
      SELECT 
        SUM(CASE 
          WHEN user_id = ? THEN (CASE WHEN borrower_type = 'lender' THEN contract_amount ELSE 0 END) 
          WHEN lender_name = ? OR lender_id_card = ? OR lender_phone = ? THEN contract_amount 
          ELSE 0 
        END) as lent_amount,
        SUM(CASE 
          WHEN user_id = ? THEN (CASE WHEN borrower_type = 'borrower' THEN contract_amount ELSE 0 END) 
          WHEN borrower_real_name = ? OR borrower_real_id_card = ? OR borrower_phone = ? THEN contract_amount 
          ELSE 0 
        END) as borrowed_amount,
        SUM(CASE 
          WHEN (user_id = ? AND borrower_type = 'lender') OR (lender_name = ? OR lender_id_card = ? OR lender_phone = ?) THEN 
            (CASE WHEN status = 3 THEN pay_amount ELSE 0 END) 
          ELSE 0 
        END) as received_amount,
        SUM(CASE 
          WHEN (user_id = ? AND borrower_type = 'lender') OR (lender_name = ? OR lender_id_card = ? OR lender_phone = ?) THEN 
            (CASE WHEN status IN (1, 2) THEN (contract_amount - IFNULL(pay_amount, 0)) ELSE 0 END) 
          ELSE 0 
        END) as receivable_amount,
        SUM(CASE 
          WHEN (user_id = ? AND borrower_type = 'borrower') OR (borrower_real_name = ? OR borrower_real_id_card = ? OR borrower_phone = ?) THEN 
            (CASE WHEN status = 3 THEN pay_amount ELSE 0 END) 
          ELSE 0 
        END) as paid_amount,
        SUM(CASE 
          WHEN (user_id = ? AND borrower_type = 'borrower') OR (borrower_real_name = ? OR borrower_real_id_card = ? OR borrower_phone = ?) THEN 
            (CASE WHEN status IN (1, 2) THEN (contract_amount - IFNULL(pay_amount, 0)) ELSE 0 END) 
          ELSE 0 
        END) as payable_amount
      FROM contracts 
      WHERE status != -1
    `,
      [
        userId,
        currentUser?.realName || "",
        currentUser?.idCard || "",
        currentUser?.phone || "",
        userId,
        currentUser?.realName || "",
        currentUser?.idCard || "",
        currentUser?.phone || "",
        userId,
        currentUser?.realName || "",
        currentUser?.idCard || "",
        currentUser?.phone || "",
        userId,
        currentUser?.realName || "",
        currentUser?.idCard || "",
        currentUser?.phone || "",
        userId,
        currentUser?.realName || "",
        currentUser?.idCard || "",
        currentUser?.phone || "",
        userId,
        currentUser?.realName || "",
        currentUser?.idCard || "",
        currentUser?.phone || "",
      ]
    );

    const fundOverview = {
      lentAmount: fundRows[0].lent_amount || 0,
      borrowedAmount: fundRows[0].borrowed_amount || 0,
      receivedAmount: fundRows[0].received_amount || 0,
      receivableAmount: fundRows[0].receivable_amount || 0,
      paidAmount: fundRows[0].paid_amount || 0,
      payableAmount: fundRows[0].payable_amount || 0,
    };

    // 获取合同统计数据
    const [statsRows] = await db.execute(
      `
      SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as executing,
        SUM(CASE WHEN DATEDIFF(NOW(), end_date) > 0 AND status IN (1, 2) THEN 1 ELSE 0 END) as overdue,
        SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) as completed
      FROM contracts 
      ${whereClause}
    `,
      params
    );

    const contractStats = {
      total: statsRows[0].total || 0,
      pending: statsRows[0].pending || 0,
      executing: statsRows[0].executing || 0,
      overdue: statsRows[0].overdue || 0,
      completed: statsRows[0].completed || 0,
    };

    res.json({
      code: 200,
      message: "获取成功",
      data: {
        fundOverview,
        contractStats,
      },
    });
  } catch (error) {
    console.error("获取仪表板数据失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
    });
  }
});

/**
 * @swagger
 * /api/contracts/{contractId}/payment-amounts:
 *   get:
 *     summary: 获取特定合同的支付金额详情
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: contractId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 合同ID
 *     responses:
 *       200:
 *         description: 成功获取合同支付金额详情
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "获取成功"
 *                 data:
 *                   type: object
 *                   properties:
 *                     contractId:
 *                       type: integer
 *                       description: 合同ID
 *                     contractNumber:
 *                       type: string
 *                       description: 合同编号
 *                     contractAmount:
 *                       type: number
 *                       description: 合同总金额
 *                     totalPaymentAmount:
 *                       type: number
 *                       description: 总支付金额（所有支付记录的总和）
 *                     paidAmount:
 *                       type: number
 *                       description: 已支付金额（状态为'paid'的支付记录总和）
 *                       example: 5000
 *                     pendingAmount:
 *                       type: number
 *                       description: 待支付金额（状态为'pending'的支付记录总和）
 *                       example: 5000
 *                     cancelledAmount:
 *                       type: number
 *                       description: 已取消金额（状态为'cancelled'的支付记录总和）
 *                     failedAmount:
 *                       type: number
 *                       description: 支付失败金额（状态为'failed'的支付记录总和）
 *                     refundedAmount:
 *                       type: number
 *                       description: 已退款金额（状态为'refunded'的支付记录总和）
 *                     remainingAmount:
 *                       type: number
 *                       description: 剩余未支付金额（合同总金额减去已支付金额）
 *                       example: 5000
 *       400:
 *         description: 参数错误
 *       404:
 *         description: 合同不存在
 *       500:
 *         description: 服务器内部错误
 */
router.get(
  "/:contractId/payment-amounts",
  authenticateToken,
  async (req, res) => {
    try {
      const { contractId } = req.params;
      const userId = req.user.id;

      // 验证合同ID
      if (!contractId || isNaN(parseInt(contractId))) {
        return res.status(400).json({
          code: 400,
          message: "参数错误：无效的合同ID",
        });
      }

      // 检查合同是否存在且用户有权限访问
      const [contractRows] = await db.execute(
        `SELECT id, contract_number, contract_amount, user_id, lender_name, borrower_real_name 
       FROM contracts 
       WHERE id = ? AND status != -1`,
        [contractId]
      );

      if (contractRows.length === 0) {
        return res.status(404).json({
          code: 404,
          message: "合同不存在",
        });
      }

      const contract = contractRows[0];

      // 获取当前用户的详细信息，用于验证权限
      const [userRows] = await db.execute(
        "SELECT idCard, phone, realName FROM user WHERE id = ?",
        [userId]
      );
      const currentUser = userRows[0];

      // 验证用户是否有权限访问该合同（创建者、出借人或借款人）
      const hasPermission =
        contract.user_id === userId ||
        (currentUser.realName &&
          contract.lender_name === currentUser.realName) ||
        (currentUser.realName &&
          contract.borrower_real_name === currentUser.realName);

      if (!hasPermission) {
        return res.status(403).json({
          code: 403,
          message: "您无权访问此合同的支付信息",
        });
      }

      // 查询该合同的所有支付记录并按状态汇总金额
      const [paymentRows] = await db.execute(
        `SELECT 
        SUM(payment_amount) as totalPaymentAmount,
        SUM(CASE WHEN status = 'paid' THEN payment_amount ELSE 0 END) as paidAmount,
        SUM(CASE WHEN status = 'pending' THEN payment_amount ELSE 0 END) as pendingAmount,
        SUM(CASE WHEN status = 'cancelled' THEN payment_amount ELSE 0 END) as cancelledAmount,
        SUM(CASE WHEN status = 'failed' THEN payment_amount ELSE 0 END) as failedAmount,
        SUM(CASE WHEN status = 'refunded' THEN payment_amount ELSE 0 END) as refundedAmount
       FROM payments 
       WHERE contract_id = ?`,
        [contractId]
      );

      const paymentData = paymentRows[0];
      const contractAmount = parseFloat(contract.contract_amount) || 0;
      const paidAmount = parseFloat(paymentData.paidAmount) || 0;
      const remainingAmount = Math.max(0, contractAmount - paidAmount);

      // 构造响应数据
      const responseData = {
        contractId: parseInt(contractId),
        contractNumber: contract.contract_number,
        contractAmount: contractAmount,
        totalPaymentAmount: parseFloat(paymentData.totalPaymentAmount) || 0,
        paidAmount: paidAmount,
        pendingAmount: parseFloat(paymentData.pendingAmount) || 0,
        cancelledAmount: parseFloat(paymentData.cancelledAmount) || 0,
        failedAmount: parseFloat(paymentData.failedAmount) || 0,
        refundedAmount: parseFloat(paymentData.refundedAmount) || 0,
        remainingAmount: remainingAmount,
      };

      res.json({
        code: 200,
        message: "获取成功",
        data: responseData,
      });
    } catch (error) {
      console.error("查询合同支付金额失败:", error);
      res.status(500).json({
        code: 500,
        message: "服务器内部错误",
        error:
          process.env.NODE_ENV === "development"
            ? error.message
            : "查询合同支付金额失败",
      });
    }
  }
);

/**
 * @swagger
 * /api/contracts/list:
 *   get:
 *     summary: 获取合同列表（包含用户创建和参与的合同）
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: status
 *         required: false
 *         schema:
 *           type: string
 *           enum: ["all", "1", "2", "3", "4", "5", "6"]
 *         description: 合同状态筛选
 *       - in: query
 *         name: page
 *         required: false
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         required: false
 *         schema:
 *           type: integer
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: search
 *         required: false
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *     responses:
 *       200:
 *         description: 成功获取合同列表（包含用户创建和参与的合同）
 */
router.get("/list", authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { status = "all", page = 1, limit = 10, search = "" } = req.query;
    const offset = (page - 1) * limit;

    // 获取当前用户的详细信息，用于匹配参与的合同
    const [userRows] = await db.execute(
      "SELECT idCard, phone, realName FROM user WHERE id = ?",
      [userId]
    );
    const currentUser = userRows[0];

    // 构建查询条件，不仅查询用户创建的合同，还要查询用户参与的合同，并且过滤掉status为-1的数据
    let whereClause = "WHERE status != -1 AND (user_id = ?";
    let params = [userId];

    // 添加用户参与的合同条件（作为借款人或出借人）
    if (
      currentUser &&
      (currentUser.idCard || currentUser.phone || currentUser.realName)
    ) {
      whereClause +=
        " OR (lender_name = ? OR lender_id_card = ? OR lender_phone = ?)";
      params.push(
        currentUser.realName || "",
        currentUser.idCard || "",
        currentUser.phone || ""
      );

      whereClause +=
        " OR (borrower_real_name = ? OR borrower_real_id_card = ? OR borrower_phone = ?)";
      params.push(
        currentUser.realName || "",
        currentUser.idCard || "",
        currentUser.phone || ""
      );
    }

    whereClause += ")";

    // 状态筛选
    if (status !== "all") {
      if (status === "1") {
        whereClause += " AND status = ?";
        params.push(1);
      } else if (status === "2") {
        whereClause += " AND status = ?";
        params.push(2);
      } else if (status === "3") {
        whereClause +=
          " AND DATEDIFF(NOW(), end_date) > 0 AND status IN (?, ?)";
        params.push(1, 2);
      } else if (status === "4") {
        whereClause += " AND status = ?";
        params.push(3);
      } else if (status === "5") {
        whereClause += " AND status = ?";
        params.push(5);
      } else if (status === "6") {
        whereClause += " AND status = ?";
        params.push(6);
      }
    }

    // 搜索筛选
    if (search) {
      whereClause += " AND (borrower_real_name LIKE ? OR lender_name LIKE ?)";
      params.push(`%${search}%`, `%${search}%`);
    }

    // 获取合同列表
    const [contracts] = await db.query(
      `
      SELECT 
        id,
        lender_name,
        borrower_real_name,
        borrower_type,
        contract_amount,
        annual_rate,
        loan_days,
        DATEDIFF(end_date, NOW()) as remaining_days,
        status,
        pay_status,
        pay_amount,
        start_date,
        end_date,
        created_at,
        contract_number
      FROM contracts 
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT ? OFFSET ?
    `,
      [...params, parseInt(limit), parseInt(offset)]
    );

    // 处理合同数据
    const formattedContracts = contracts.map((contract) => {
      // 计算逾期天数
      const endDate = new Date(contract.end_date);
      const today = new Date();
      const overdueDays = Math.max(
        0,
        Math.floor((today - endDate) / (1000 * 60 * 60 * 24))
      );

      // 判断当前用户是否为出借人，只有出借人才能操作
      const canOperate =
        currentUser &&
        currentUser.realName &&
        contract.lender_name &&
        currentUser.realName === contract.lender_name;

      return {
        id: contract.id,
        contractNumber: contract.contract_number,

        borrowerType: contract.borrower_type,
        borrowerRealName: contract.borrower_real_name,
        lenderName: contract.lender_name,
        amount: contract.contract_amount,
        interestRate: contract.annual_rate,
        duration: contract.loan_days,
        overdueDays: overdueDays,
        status: contract.status,
        payStatus: contract.pay_status,
        payAmount: contract.pay_amount,
        startDate: new Date(contract.start_date).toLocaleDateString("zh-CN"),
        endDate: new Date(contract.end_date).toLocaleDateString("zh-CN"),
        createdAt: new Date(contract.created_at).toLocaleString("zh-CN"),
        canOperate: canOperate,
      };
    });

    // 获取总数
    const [countResult] = await db.execute(
      `
      SELECT COUNT(*) as total FROM contracts ${whereClause}
    `,
      params
    );

    const total = countResult[0].total;

    res.json({
      code: 200,
      message: "获取成功",
      data: {
        contracts: formattedContracts,
        total: total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error("获取合同列表失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
    });
  }
});

/**
 * @swagger
 * /api/contracts/create:
 *   post:
 *     summary: 创建新合同
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - contract_name
 *               - counterpart_name
 *               - amount
 *               - interest_rate
 *               - duration_days
 *               - contract_type
 *             properties:
 *               contract_name:
 *                 type: string
 *                 example: "李*兵与廖*的借款合同"
 *               counterpart_name:
 *                 type: string
 *                 example: "廖某"
 *               amount:
 *                 type: number
 *                 example: 10000
 *               interest_rate:
 *                 type: number
 *                 example: 0
 *               duration_days:
 *                 type: integer
 *                 example: 11
 *               contract_type:
 *                 type: string
 *                 enum: [lend, borrow]
 *                 example: "lend"
 *               description:
 *                 type: string
 *                 example: "借款合同描述"
 *     responses:
 *       201:
 *         description: 合同创建成功
 */
router.post("/create", authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const {
      contract_name,
      counterpart_name,
      amount,
      interest_rate,
      duration_days,
      contract_type,
      description = "",
    } = req.body;

    // 验证必填字段
    if (
      !contract_name ||
      !counterpart_name ||
      !amount ||
      duration_days === undefined ||
      !contract_type
    ) {
      return res.status(400).json({
        code: 400,
        message: "缺少必填字段",
      });
    }

    const start_date = new Date();
    const end_date = new Date(
      start_date.getTime() + duration_days * 24 * 60 * 60 * 1000
    );
    const remaining_days = duration_days;

    const [result] = await db.execute(
      `
      INSERT INTO contracts (
        user_id, contract_name, counterpart_name, amount, interest_rate,
        duration_days, remaining_days, contract_type, description,
        start_date, end_date, status, pay_status, created_at, updated_at, pay_amount
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 1, NOW(), NOW(),1)
    `,
      [
        userId,
        contract_name,
        counterpart_name,
        amount,
        interest_rate,
        duration_days,
        remaining_days,
        contract_type,
        description,
        start_date,
        end_date,
        pay_status,
      ]
    );

    res.status(201).json({
      code: 201,
      message: "合同创建成功",
      data: {
        contractId: result.insertId,
      },
    });
  } catch (error) {
    console.error("创建合同失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
    });
  }
});

/**
 * @swagger
 * /api/contracts/{id}:
 *   get:
 *     summary: 获取合同详情
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 合同ID
 *     responses:
 *       200:
 *         description: 成功获取合同详情
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "获取成功"
 *                 data:
 *                   type: object
 *                   properties:
 *                     id:
 *                       type: integer
 *                       example: 1
 *                     contractNumber:
 *                       type: string
 *                       example: "HT2025306827"
 *                     title:
 *                       type: string
 *                       example: "张三的借款合同"
 *                     amount:
 *                       type: string
 *                       example: "100000"
 *                     lenderName:
 *                       type: string
 *                       example: "张三"
 *                     borrowerRealName:
 *                       type: string
 *                       example: "李四"
 *                     status:
 *                       type: integer
 *                       example: 1
 *       404:
 *         description: 合同不存在
 *       500:
 *         description: 服务器内部错误
 */
router.get("/contracts/:id", authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const contractId = req.params.id;

    const [contracts] = await db.execute(
      `
      SELECT *, pay_status FROM contracts 
      WHERE id = ? AND user_id = ?
    `,
      [contractId, userId]
    );

    if (contracts.length === 0) {
      return res.status(404).json({
        code: 404,
        message: "合同不存在",
      });
    }

    const contract = contracts[0];

    // 计算逾期天数
    const endDate = new Date(contract.end_date);
    const today = new Date();
    const overdueDays = Math.max(
      0,
      Math.floor((today - endDate) / (1000 * 60 * 60 * 24))
    );

    // 格式化合同详情数据
    const formattedContract = {
      id: contract.id,
      contractNumber: contract.contract_number,
      title: `${
        contract.borrower_type === "lender"
          ? contract.borrower_real_name
          : contract.lender_name
      }的借款合同`,
      type: contract.contract_type === "lender" ? "出借" : "借款",
      amount: contract.contract_amount,
      amountInWords: contract.amount_in_words,
      interestRate: `${contract.annual_rate}%`,
      duration: `${contract.loan_days}天`,
      overdueDays: overdueDays,
      status: contract.status,
      payStatus: contract.pay_status,
      lenderName: contract.lender_name,
      lenderIdCard: contract.lender_id_card,
      borrowerType: contract.borrower_type,
      borrowerRealName: contract.borrower_real_name,
      borrowerRealIdCard: contract.borrower_real_id_card,
      repaymentMethod: contract.repayment_method,
      contractReason: contract.contract_reason,
      additionalNotes: contract.additional_notes,
      startDate: new Date(contract.start_date).toLocaleDateString("zh-CN"),
      endDate: new Date(contract.end_date).toLocaleDateString("zh-CN"),
      payAmount: contract.pay_amount || 0,
      contractType: contract.contract_type,
      createdAt: new Date(contract.created_at).toLocaleString("zh-CN"),
      updatedAt: new Date(contract.updated_at).toLocaleString("zh-CN"),
    };

    res.json({
      code: 200,
      message: "获取成功",
      data: formattedContract,
    });
  } catch (error) {
    console.error("获取合同详情失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
    });
  }
});

/**
 * @swagger
 * /api/contracts/generate:
 *   post:
 *     summary: 生成合同文档
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               lenderName:
 *                 type: string
 *                 description: 出借人姓名
 *                 example: "张三"
 *               lenderIdCard:
 *                 type: string
 *                 description: 出借人身份证号
 *                 example: "110101199001011234"
 *               borrowerRealName:
 *                 type: string
 *                 description: 借款人姓名
 *                 example: "李四"
 *               borrowerType:
 *                 type: number
 *                 description: 借款人类型
 *                 example: 1
 *               contractAmount:
 *                 type: string
 *                 description: 合同金额
 *                 example: "100000"
 *               amountInWords:
 *                 type: string
 *                 description: 金额大写
 *                 example: "壹拾万元整"
 *               repaymentMethod:
 *                 type: string
 *                 description: 还款方式
 *                 example: "一次性还本付息"
 *               startDate:
 *                 type: string
 *                 description: 开始日期
 *                 example: "2024-01-01"
 *               endDate:
 *                 type: string
 *                 description: 结束日期
 *                 example: "2024-12-31"
 *               loanDays:
 *                 type: string
 *                 description: 借款天数
 *                 example: "365"
 *               annualRate:
 *                 type: string
 *                 description: 年利率
 *                 example: "0"
 *               contractReason:
 *                 type: string
 *                 description: 合同原因
 *                 example: "周转"
 *               additionalNotes:
 *                 type: string
 *                 description: 附加说明
 *                 example: ""
 *     responses:
 *       200:
 *         description: 合同生成成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "合同生成成功"
 *                 data:
 *                   type: object
 *                   properties:
 *                     contractId:
 *                       type: integer
 *                       example: 1
 *                     downloadUrl:
 *                       type: string
 *                       example: "/api/documents/download/contract_20240101_123456.docx"
 *       400:
 *         description: 请求参数错误
 *       401:
 *         description: 未授权
 *       500:
 *         description: 服务器内部错误
 */
router.post("/generate", authenticateToken, async (req, res) => {
  try {
    const {
      lenderName,
      lenderIdCard,
      lenderPhone,
      borrowerRealName,
      borrowerType,
      borrowerPhone,
      borrowerRealIdCard,
      contractAmount,
      amountInWords,
      repaymentMethod,
      startDate,
      endDate,
      loanDays,
      annualRate,
      contractReason,
      additionalNotes,
      contractType,
      status,
    } = req.body;
    let payAmount = req.body.payAmount;
    let requiredFields = {};
    //根据borrowerType 验证不同的必填字段
    if (borrowerType === "lender") {
      // 验证必填字段
      requiredFields = {
        lenderName: "出借人姓名",
        lenderIdCard: "出借人身份证号",
        borrowerType: "借款人类型",
        contractAmount: "合同金额",
        amountInWords: "金额大写",
        startDate: "开始日期",
        endDate: "结束日期",
        loanDays: "借款天数",
      };
    } else {
      requiredFields = {
        borrowerRealName: "借款人姓名",
        borrowerRealIdCard: "借款人身份证号",
        borrowerType: "借款人类型",
        contractAmount: "合同金额",
        amountInWords: "金额大写",
        startDate: "开始日期",
        endDate: "结束日期",
        loanDays: "借款天数",
      };
    }

    // 判断 borrowerType 是 lender 还是 borrower 通过实名接口验证不同的身份信息是否正确
    if (contractType == "由我填写") {
      if (borrowerType === "lender") {
        // 验证借款人身份信息
        const borrowerAuthResult = await verifyIdentity(
          borrowerRealName,
          borrowerRealIdCard
        );
        if (!borrowerAuthResult.success) {
          return res.status(200).json({
            code: 400,
            message: "借款人身份验证失败,请检查填入的身份信息",
            error: borrowerAuthResult.error,
          });
        }
      } else {
        // 验证出借人身份信息
        const lenderAuthResult = await verifyIdentity(lenderName, lenderIdCard);
        if (!lenderAuthResult.success) {
          return res.status(200).json({
            code: 400,
            message: "出借人身份验证失败,请检查填入的身份信息",
            error: lenderAuthResult.error,
          });
        }
      }
    }

    for (const [field, fieldName] of Object.entries(requiredFields)) {
      if (!req.body[field]) {
        return res.status(400).json({
          code: 400,
          message: `${fieldName}不能为空`,
        });
      }
    }
    // 获取用户ID（从JWT token中获取）
    const userId = req.user.id;

    // 生成合同编号
    const contractNumber = `HT${new Date().getFullYear()}${String(
      Date.now()
    ).slice(-6)}`;
    // 计算合同费用
    // 查询有效的合同设置
    const [settingsRows] = await db.execute(
      `SELECT id, min_amount, max_amount, fee_amount, fee_type, percentage, status, remark
       FROM contract_settings 
       WHERE status = 1
       ORDER BY min_amount ASC`
    );

    // 检查是否有有效的合同设置
    if (!settingsRows || settingsRows.length === 0) {
      return res.status(400).json({
        code: 400,
        message: "系统配置错误",
        error: "未找到有效的合同费用设置，请联系管理员配置费用标准",
      });
    }

    const contractAmounts = parseFloat(contractAmount);
    const { contractFee, feeCalculation } = calculateContractFee(
      contractAmounts,
      settingsRows
    );

    // 检查是否找到适用的费用配置，未找到则使用默认费用10元
    let finalContractFee = contractFee;
    if (!feeCalculation.applicable) {
      finalContractFee = 10; // 默认费用10元
      console.log(
        `合同金额 ${contractAmount} 元未找到对应的费用配置，使用默认费用10元`
      );
    }
    payAmount = finalContractFee;
    // 保存合同信息到数据库
    const insertSql = `
      INSERT INTO contracts (
        user_id, contract_number, lender_name, lender_id_card, lender_phone, borrower_real_name, borrower_type,
        borrower_real_id_card, borrower_phone, contract_amount, amount_in_words, repayment_method,
        start_date, end_date, loan_days, annual_rate, interest_rate, contract_reason,
          additional_notes, status, pay_amount, pay_status, contract_type
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;

    const [result] = await db.execute(insertSql, [
      userId,
      contractNumber,
      lenderName || "",
      lenderIdCard || "",
      lenderPhone || "",
      borrowerRealName || "",
      borrowerType || "",
      borrowerRealIdCard || "",
      borrowerPhone || "",
      contractAmount || 0,
      amountInWords || "",
      repaymentMethod || "",
      startDate || "",
      endDate || "",
      loanDays || 0,
      annualRate || "0",
      annualRate || "0",
      contractReason || "周转",
      additionalNotes || "",
      status || 1, // status
      payAmount || 0, // pay_amount
      1, // pay_status 初始化为1(未支付)
      contractType || 1,
    ]);

    const contractId = result.insertId;

    // 准备合同数据用于生成文档
    // 处理空值，确保所有字段都有有效值
    // 使用与/fileUpdate接口兼容的数据结构
    const contractData = {
      contractNumber: contractNumber || "",
      lenderName: lenderName || "",
      lenderIdCard: lenderIdCard || "",
      lenderPhone: lenderPhone || "",
      borrowerRealName: borrowerRealName || "",
      borrowerPhone: borrowerPhone || "",
      borrowerType: borrowerType || "个人",
      borrowerRealIdCard: borrowerRealIdCard || "",
      contractAmount: contractAmount || "0",
      amountInWords: amountInWords || "零元整",
      repaymentMethod: repaymentMethod || "一次性还本付息",
      startDate: startDate || new Date().toLocaleDateString("zh-CN"),
      endDate: endDate || new Date().toLocaleDateString("zh-CN"),
      loanDays: loanDays || "0",
      annualRate: annualRate || "0",
      contractReason: contractReason || "周转",
      additionalNotes: additionalNotes || "无",
      createdDate: new Date().toLocaleDateString("zh-CN"),
      createdTime: new Date().toLocaleTimeString("zh-CN"),
    };
    console.log(contractData);
    // 调用文档生成服务
    const WordProcessor = require("../utils/wordProcessor");
    const path = require("path");
    const fs = require("fs");

    const templatePath = path.join(__dirname, "../模版.docx");
    const outputFileName = `contract_${new Date().getFullYear()}${String(
      new Date().getMonth() + 1
    ).padStart(2, "0")}${String(new Date().getDate()).padStart(
      2,
      "0"
    )}_${contractId}.docx`;
    const outputPath = path.join("/home/output/words", outputFileName);
    // 确保输出目录存在
    const outputDir = path.dirname(outputPath);
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }

    // 生成合同文档
    const docResult = await WordProcessor.processTemplate(
      templatePath,
      contractData,
      outputPath
    );

    if (!docResult.success) {
      // 如果文档生成失败，删除数据库记录
      await db.execute("DELETE FROM contracts WHERE id = ?", [contractId]);
      return res.status(500).json({
        code: 500,
        message: "合同文档生成失败",
        error: docResult.message,
      });
    }

    // 更新合同状态为已生成 更新合同文档路径
    await db.execute(
      "UPDATE contracts SET status = ?, contract_file = ?, pay_status = ? WHERE id = ?",
      [
        1,
        outputFileName,
        1, // 设置pay_status默认值为1
        contractId,
      ]
    );

    res.json({
      code: 200,
      message: "合同生成成功",
      data: {
        contractId: contractId,
        contractNumber: contractNumber,
        downloadUrl: outputPath,
        contractFile: outputFileName,
        fileName: outputFileName,
      },
    });
  } catch (error) {
    console.error("生成合同失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development" ? error.message : "生成合同失败",
    });
  }
});

/**
 * @swagger
 * /api/contracts/updateParties:
 *   put:
 *     summary: 修改合同内容 - 更新借款人信息、出借人信息及合同文件
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               contractId:
 *                 type: integer
 *                 description: 合同ID
 *                 example: 1
 *               borrowerRealName:
 *                 type: string
 *                 description: 借款人真实姓名
 *                 example: "李四"
 *               borrowerRealIdCard:
 *                 type: string
 *                 description: 借款人身份证号
 *                 example: "110101199001011234"
 *               lenderName:
 *                 type: string
 *                 description: 出借人姓名
 *                 example: "张三"
 *               lenderIdCard:
 *                 type: string
 *                 description: 出借人身份证号
 *                 example: "110101198001011234"
 *               borrowerType:
 *                 type: string
 *                 description: 借款人类型
 *                 example: "个人"
 *               contractFile:
 *                 type: string
 *                 description: 合同文件路径（可选，提供则更新合同文件）
 *                 example: "contract_123.docx"
 *               contractNumber:
 *                 type: string
 *                 description: 合同编号（可选，用于文件生成）
 *                 example: "HT2023001"
 *               lenderPhone:
 *                 type: string
 *                 description: 出借人电话（可选，用于文件生成）
 *                 example: "13900139000"
 *               borrowerPhone:
 *                 type: string
 *                 description: 借款人电话（可选，用于文件生成）
 *                 example: "13800138000"
 *               contractAmount:
 *                 type: string
 *                 description: 合同金额（可选，用于文件生成）
 *                 example: "10000"
 *               amountInWords:
 *                 type: string
 *                 description: 大写金额（可选，用于文件生成）
 *                 example: "壹万元整"
 *               repaymentMethod:
 *                 type: string
 *                 description: 还款方式（可选，用于文件生成）
 *                 example: "一次性还本付息"
 *               startDate:
 *                 type: string
 *                 description: 开始日期（可选，用于文件生成）
 *                 example: "2023-01-01"
 *               endDate:
 *                 type: string
 *                 description: 结束日期（可选，用于文件生成）
 *                 example: "2023-12-31"
 *               loanDays:
 *                 type: string
 *                 description: 借款天数（可选，用于文件生成）
 *                 example: "365"
 *               annualRate:
 *                 type: string
 *                 description: 年利率（可选，用于文件生成）
 *                 example: "8"
 *               contractReason:
 *                 type: string
 *                 description: 借款原因（可选，用于文件生成）
 *                 example: "周转"
 *               additionalNotes:
 *                 type: string
 *                 description: 附加说明（可选，用于文件生成）
 *                 example: "无"
 *               extendEndDate:
 *                 type: string
 *                 format: date
 *                 description: 展期截止日期（当status=6时使用）
 *                 example: "2025-12-31"
 *     responses:
 *       200:
 *         description: 合同信息更新成功或部分成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "合同信息和文件更新成功"
 *                 data:
 *                   type: object
 *                   properties:
 *                     contractId:
 *                       type: integer
 *                       example: 1
 *                     fileUpdateError:
 *                       type: string
 *                       description: 文件更新失败时的错误信息
 *       400:
 *         description: 请求参数错误
 *       403:
 *         description: 无权访问此合同
 *       404:
 *         description: 未找到指定的合同或文件
 *       500:
 *         description: 服务器内部错误
 */
router.put("/updateParties", authenticateToken, async (req, res) => {
  try {
    const {
      contractId,
      borrowerRealName,
      borrowerRealIdCard,
      lenderName,
      lenderIdCard,
      borrowerType,
      // 文件相关参数
      contractFile,
      contractNumber,
      lenderPhone,
      borrowerPhone,
      contractAmount,
      amountInWords,
      repaymentMethod,
      startDate,
      loanDays,
      annualRate,
      contractReason,
      additionalNotes,
      extendEndDate,
      endDate: reqEndDate, // 重命名原始字段以避免与可变变量冲突
      status: reqStatus, // 重命名原始字段以避免与可变变量冲突
    } = req.body;

    // 使用let声明可变变量
    let endDate = reqEndDate;
    let status = reqStatus === 1 ? 2 : reqStatus;
    const userId = req.user.id;

    // 参数验证
    if (!contractId || isNaN(parseInt(contractId))) {
      return res.status(400).json({
        code: 400,
        message: "合同ID不能为空",
      });
    }

    // 检查是否有可更新的字段
    const hasUpdateFields =
      borrowerRealName !== undefined ||
      borrowerRealIdCard !== undefined ||
      lenderName !== undefined ||
      lenderIdCard !== undefined;

    if (!hasUpdateFields) {
      return res.status(400).json({
        code: 400,
        message: "至少需要提供一个要更新的字段",
      });
    }
    // 检查合同是否存在
    const [contractRows] = await db.execute(
      "SELECT id, user_id FROM contracts WHERE id = ?",
      [contractId]
    );

    if (!contractRows || contractRows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: "未找到指定的合同",
      });
    }
    if (borrowerType === "lender") {
      // 验证借款人身份信息
      const borrowerAuthResult = await verifyIdentity(
        borrowerRealName,
        borrowerRealIdCard
      );
      if (!borrowerAuthResult.success) {
        return res.status(200).json({
          code: 400,
          message: "借款人身份验证失败,请检查填入的身份信息",
          error: borrowerAuthResult.error,
        });
      }
    } else {
      // 验证出借人身份信息
      const lenderAuthResult = await verifyIdentity(lenderName, lenderIdCard);
      if (!lenderAuthResult.success) {
        return res.status(200).json({
          code: 400,
          message: "出借人身份验证失败,请检查填入的身份信息",
          error: lenderAuthResult.error,
        });
      }
    }
    // 更新展期字段
    if (status === 6) {
      // 使用extendEndDate参数更新endDate
      if (extendEndDate) {
        endDate = extendEndDate;
      }
      status = 6; // 确保状态设置为6
    }
    // 构建更新SQL语句和参数
    let updateSql = "UPDATE contracts SET ";
    const updateParams = [];
    const fieldsToUpdate = [];

    if (borrowerRealName !== undefined) {
      fieldsToUpdate.push("borrower_real_name = ?");
      updateParams.push(borrowerRealName);
    }

    if (borrowerRealIdCard !== undefined) {
      fieldsToUpdate.push("borrower_real_id_card = ?");
      updateParams.push(borrowerRealIdCard);
    }

    if (lenderName !== undefined) {
      fieldsToUpdate.push("lender_name = ?");
      updateParams.push(lenderName);
    }

    if (lenderIdCard !== undefined) {
      fieldsToUpdate.push("lender_id_card = ?");
      updateParams.push(lenderIdCard);
    }

    // 如果传入了status参数，更新status
    if (reqStatus !== undefined) {
      fieldsToUpdate.push("status = ?");
      updateParams.push(status);
    }

    // 如果是展期操作，同时更新endDate
    if (status === 6 && endDate) {
      fieldsToUpdate.push("end_date = ?");
      updateParams.push(endDate);
    }

    // 添加更新时间
    fieldsToUpdate.push("updated_at = CURRENT_TIMESTAMP");

    // 完成SQL语句
    updateSql += fieldsToUpdate.join(", ") + " WHERE id = ?";
    updateParams.push(contractId);

    // 执行更新操作
    await db.execute(updateSql, updateParams);

    // 记录日志
    console.log(`合同信息更新成功，合同ID: ${contractId}，用户ID: ${userId}`);

    // 返回成功响应
    // 如果提供了合同文件参数，同时更新合同文件
    if (contractFile) {
      try {
        // 获取完整的文件路径
        const outputFileName = contractFile;
        const filePath = path.join("/home/output/words", outputFileName);
        console.log(filePath);
        // 检查文件是否存在
        if (!fs.existsSync(filePath)) {
          return res.status(404).json({
            code: 404,
            message: "文件不存在",
            data: {
              contractId: parseInt(contractId),
            },
          });
        }

        // 确保输出目录存在
        const outputDir = path.dirname(filePath);
        if (!fs.existsSync(outputDir)) {
          fs.mkdirSync(outputDir, { recursive: true });
        }
        // 使用与/fileUpdate接口兼容的数据结构
        const contractData = {
          contractNumber: contractNumber || "",
          lenderName: lenderName || "",
          lenderIdCard: lenderIdCard || "",
          lenderPhone: lenderPhone || "",
          borrowerRealName: borrowerRealName || "",
          borrowerPhone: borrowerPhone || "",
          borrowerType: borrowerType || "个人",
          borrowerRealIdCard: borrowerRealIdCard || "",
          contractAmount: contractAmount || "0",
          amountInWords: amountInWords || "零元整",
          repaymentMethod: repaymentMethod || "一次性还本付息",
          startDate: startDate || new Date().toLocaleDateString("zh-CN"),
          endDate: endDate || new Date().toLocaleDateString("zh-CN"),
          loanDays: loanDays || "0",
          annualRate: annualRate || "0",
          contractReason: contractReason || "周转",
          additionalNotes: additionalNotes || "无",
          createdDate: new Date().toLocaleDateString("zh-CN"),
          createdTime: new Date().toLocaleTimeString("zh-CN"),
          // 添加合同ID，使其在文档中可访问
          contractId: contractId,
        };
        // 使用WordProcessor更新文档
        // 注意：应该使用固定的模板文件，而不是输出文件路径作为模板
        const templatePath = path.join(__dirname, "../", "模版.docx");
        const result = await WordProcessor.processTemplate(
          templatePath,
          contractData,
          filePath
        );

        if (result.success) {
          res.json({
            code: 200,
            message: "合同信息和文件更新成功",
            data: {
              contractId: parseInt(contractId),
            },
          });
        } else {
          // 文件更新失败但数据库已更新成功，返回部分成功信息
          res.status(200).json({
            code: 200,
            message: "合同信息更新成功，但文件更新失败",
            data: {
              contractId: parseInt(contractId),
              fileUpdateError: result.message || "文件更新失败",
            },
          });
        }
      } catch (fileError) {
        console.error("更新合同文件时出错:", fileError);
        // 文件处理出错但数据库已更新成功，返回部分成功信息
        res.status(200).json({
          code: 200,
          message: "合同信息更新成功，但文件处理出错",
          data: {
            contractId: parseInt(contractId),
            fileUpdateError:
              process.env.NODE_ENV === "development"
                ? fileError.message
                : "文件处理出错",
          },
        });
      }
    } else {
      // 不更新文件，只返回数据库更新成功
      res.json({
        code: 200,
        message: "合同信息更新成功",
        data: {
          contractId: parseInt(contractId),
        },
      });
    }
  } catch (error) {
    console.error("更新合同信息失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development"
          ? error.message
          : "更新合同信息失败",
    });
  }
});

/**
 * @swagger
 * /api/contracts/number/{contractNumber}:
 *   get:
 *     summary: 根据合同编号查询合同详情
 *     tags: [Contracts]
 *     parameters:
 *       - in: path
 *         name: contractNumber
 *         required: true
 *         schema:
 *           type: string
 *         description: 合同编号
 *         example: "HT202400001"
 *     responses:
 *       200:
 *         description: 查询成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "查询成功"
 *                 data:
 *                   type: object
 *                   properties:
 *                     id:
 *                       type: integer
 *                       example: 1
 *                     contractNumber:
 *                       type: string
 *                       example: "HT202400001"
 *                     lenderName:
 *                       type: string
 *                       example: "张三"
 *                     borrowerRealName:
 *                       type: string
 *                       example: "李四"
 *                     contractAmount:
 *                       type: string
 *                       example: "100000"
 *                     status:
 *                       type: string
 *                       example: "generated"
 *                     contractFee:
 *                       type: number
 *                       example: 500
 *                       description: "计算出的合同费用"
 *                     feeCalculation:
 *                       type: object
 *                       properties:
 *                         applicable:
 *                           type: boolean
 *                           example: true
 *                           description: "是否适用费用设置"
 *                         feeType:
 *                           type: string
 *                           example: "fixed"
 *                           description: "费用类型：fixed(固定费用)或percentage(百分比费用)"
 *                         feeAmount:
 *                           type: number
 *                           example: 500
 *                           description: "固定费用金额"
 *                         percentage:
 *                           type: number
 *                           example: 0.005
 *                           description: "百分比费率"
 *                         calculatedFee:
 *                           type: number
 *                           example: 500
 *                           description: "计算出的费用"
 *                         remark:
 *                           type: string
 *                           example: "合同费用备注"
 *                     contractSettings:
 *                       type: array
 *                       description: "合同设置列表"
 *                       items:
 *                         type: object
 *                         properties:
 *                           id:
 *                             type: integer
 *                           min_amount:
 *                             type: number
 *                           max_amount:
 *                             type: number
 *                           fee_amount:
 *                             type: number
 *                           fee_type:
 *                             type: string
 *                           percentage:
 *                             type: number
 *                           status:
 *                             type: integer
 *                           remark:
 *                             type: string
 *       404:
 *         description: 合同不存在
 *       500:
 *         description: 服务器内部错误
 */
// 计算合同费用的辅助函数
function calculateContractFee(contractAmount, settings) {
  const feeCalculation = {
    applicable: false,
    feeType: null,
    feeAmount: 0,
    percentage: 0,
    calculatedFee: 0,
    remark: "",
  };

  if (!settings || settings.length === 0) {
    return { contractFee: 0, feeCalculation };
  }

  // 查找适用的费用设置
  const applicableSetting = settings.find((setting) => {
    const minAmount = parseFloat(setting.min_amount) || 0;
    const maxAmount = parseFloat(setting.max_amount) || Infinity;
    return contractAmount >= minAmount && contractAmount <= maxAmount;
  });

  if (!applicableSetting) {
    return { contractFee: 0, feeCalculation };
  }

  feeCalculation.applicable = true;
  feeCalculation.feeType = applicableSetting.fee_type;
  feeCalculation.feeAmount = parseFloat(applicableSetting.fee_amount) || 0;
  feeCalculation.percentage = parseFloat(applicableSetting.percentage) || 0;
  feeCalculation.remark = applicableSetting.remark || "";

  let contractFee = 0;

  // 根据费用类型计算费用
  if (applicableSetting.fee_type === "fixed") {
    contractFee = feeCalculation.feeAmount;
  } else if (applicableSetting.fee_type === "percentage") {
    contractFee = contractAmount * (feeCalculation.percentage / 100);
  }

  feeCalculation.calculatedFee = contractFee;

  return { contractFee, feeCalculation };
}

// 格式化日期的辅助函数
function formatDateTime(date, type = "datetime") {
  if (type === "date") {
    return new Date(date).toLocaleDateString("zh-CN");
  }
  return new Date(date).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
}

router.get("/number/:contractNumber", authenticateToken, async (req, res) => {
  try {
    const { contractNumber } = req.params;

    // 验证合同编号格式
    if (!contractNumber || !contractNumber.match(/^HT\d{10}$/)) {
      return res.status(400).json({
        code: 400,
        message: "合同编号格式不正确",
      });
    }

    // 查询合同详情
    const [contractRows] = await db.execute(
      `SELECT 
        id, user_id, contract_number, lender_name, lender_id_card,
        borrower_type, borrower_real_name, borrower_real_id_card,
        contract_amount, amount_in_words, repayment_method, start_date, end_date,
        loan_days, annual_rate, contract_reason, additional_notes, status,
        pay_status, pay_amount, created_at, updated_at, contract_file, contract_type, extend_end_date
      FROM contracts 
      WHERE contract_number = ?`,
      [contractNumber]
    );

    if (contractRows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: "合同不存在",
      });
    }

    const contract = contractRows[0];
    if (contract.status == -1) {
      return res.status(400).json({
        code: 400,
        message: "合同已被删除",
      });
    }
    // 构建响应数据
    const responseData = {
      // 基本信息
      id: contract.id,
      contractNumber: contract.contract_number,
      userId: contract.user_id,

      // 当事人信息
      lenderName: contract.lender_name,
      lenderIdCard: contract.lender_id_card,
      borrowerRealName: contract.borrower_real_name,
      borrowerType: contract.borrower_type,
      borrowerRealIdCard: contract.borrower_real_id_card,

      // 合同条款
      contractAmount: contract.contract_amount,
      amountInWords: contract.amount_in_words,
      repaymentMethod: contract.repayment_method,
      startDate: formatDateTime(contract.start_date, "date"),
      endDate: formatDateTime(contract.end_date, "date"),
      loanDays: contract.loan_days,
      annualRate: contract.annual_rate,
      contractReason: contract.contract_reason,
      additionalNotes: contract.additional_notes,
      contractFile: contract.contract_file,
      // 状态和费用
      status: contract.status,
      payStatus: contract.pay_status,
      payAmount: contract.pay_amount, // 计算得出的费用金额
      contractType: contract.contract_type,
      // 时间信息
      createdAt: formatDateTime(contract.created_at),
      updatedAt: formatDateTime(contract.updated_at),
      extendEndDate: contract.extend_end_date
        ? formatDateTime(contract.extend_end_date)
        : "",
    };

    res.json({
      code: 200,
      message: "查询成功",
      data: responseData,
    });
  } catch (error) {
    console.error("查询合同失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development" ? error.message : "查询合同失败",
    });
  }
});

/**
 * @swagger
 * /api/contracts/settings:
 *   get:
 *     summary: 获取合同设置
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 成功获取合同设置
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "获取成功"
 *                 data:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       id:
 *                         type: integer
 *                         example: 1
 *                       min_amount:
 *                         type: number
 *                         example: 1000
 *                       max_amount:
 *                         type: number
 *                         example: 1000000
 *                       fee_amount:
 *                         type: number
 *                         example: 100
 *                       fee_type:
 *                         type: string
 *                         example: "fixed"
 *                       percentage:
 *                         type: number
 *                         example: 0.05
 *                       status:
 *                         type: integer
 *                         example: 1
 *                       remark:
 *                         type: string
 *                         example: "合同设置备注"
 *       500:
 *         description: 服务器内部错误
 */
router.get("/settings", authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;

    // 查询合同设置
    const [rows] = await db.execute(
      `SELECT 
         id,
         min_amount,
         max_amount,
         fee_amount,
         fee_type,
         percentage,
         status,
         remark,
         create_time,
         update_time
       FROM contract_settings 
       ORDER BY id ASC`
    );

    // 构建响应数据
    const responseData = rows.map((item) => ({
      id: item.id,
      minAmount: item.min_amount,
      maxAmount: item.max_amount,
      feeAmount: item.fee_amount,
      feeType: item.fee_type,
      percentage: item.percentage,
      status: item.status,
      remark: item.remark,
      createTime: formatDateTime(item.create_time),
      updateTime: formatDateTime(item.update_time),
    }));

    res.json({
      code: 200,
      message: "获取成功",
      data: responseData,
    });
  } catch (error) {
    console.error("获取合同设置失败:", error);
    res.status(200).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development"
          ? error.message
          : "获取合同设置失败",
    });
  }
});

/**
 * @swagger
 * /api/contracts/addSettings:
 *   post:
 *     summary: 新增合同设置
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - minAmount
 *               - maxAmount
 *               - feeAmount
 *               - feeType
 *               - percentage
 *               - status
 *             properties:
 *               minAmount:
 *                 type: number
 *                 example: 1000
 *               maxAmount:
 *                 type: number
 *                 example: 100000
 *               feeAmount:
 *                 type: number
 *                 example: 100
 *               feeType:
 *                 type: string
 *                 example: "fixed"
 *               percentage:
 *                 type: number
 *                 example: 0.05
 *               status:
 *                 type: integer
 *                 example: 1
 *               remark:
 *                 type: string
 *                 example: "合同设置备注"
 *     responses:
 *       200:
 *         description: 新增成功
 *       400:
 *         description: 参数错误
 *       500:
 *         description: 服务器内部错误
 */
router.post("/addSettings", authenticateToken, async (req, res) => {
  try {
    const {
      minAmount,
      maxAmount,
      feeAmount,
      feeType,
      percentage,
      status,
      remark = "",
    } = req.body;

    // 参数验证
    if (
      !minAmount ||
      !maxAmount ||
      !feeAmount ||
      !feeType ||
      percentage === undefined ||
      status === undefined
    ) {
      return res.status(200).json({
        code: 201,
        message: "参数不完整",
        error:
          "minAmount, maxAmount, feeAmount, feeType, percentage, status 为必填字段",
      });
    }

    if (minAmount >= maxAmount) {
      return res.status(200).json({
        code: 201,
        message: "参数错误",
        error: "最小金额必须小于最大金额",
      });
    }

    // 验证fee_type字段
    if (feeType !== "fixed" && feeType !== "percentage") {
      return res.status(200).json({
        code: 201,
        message: "参数错误",
        error: "fee_type只能是fixed或percentage",
      });
    }

    // 验证固定类型和比例类型只能开启一个
    if (feeType === "fixed" && (feeAmount <= 0 || percentage !== 0)) {
      return res.status(200).json({
        code: 201,
        message: "参数错误",
        error: "固定类型时，feeAmount必须大于0，percentage必须为0",
      });
    }

    // 验证同类型是否存在相同金额区间
    const [existingSameType] = await db.query(
      "SELECT id, min_amount, max_amount FROM contract_settings WHERE fee_type = ?",
      [feeType]
    );

    for (const existing of existingSameType) {
      // 检查金额区间是否重叠
      if (
        (minAmount >= existing.min_amount && minAmount < existing.max_amount) ||
        (maxAmount > existing.min_amount && maxAmount <= existing.max_amount) ||
        (minAmount <= existing.min_amount && maxAmount >= existing.max_amount)
      ) {
        return res.status(200).json({
          code: 201,
          message: "参数错误",
          error: `同类型已存在重叠的金额区间，冲突区间：${existing.min_amount}-${existing.max_amount}`,
        });
      }
    }

    // 插入数据
    const [result] = await db.query(
      `INSERT INTO contract_settings 
       (min_amount, max_amount, fee_amount, fee_type, percentage, status, remark, create_time, update_time) 
       VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
      [minAmount, maxAmount, feeAmount, feeType, percentage, status, remark]
    );

    res.json({
      code: 200,
      message: "新增成功",
      data: {
        id: result.insertId,
      },
    });
  } catch (error) {
    console.error("新增合同设置失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development"
          ? error.message
          : "新增合同设置失败",
    });
  }
});

/**
 * @swagger
 * /api/contracts/delSettings:
 *   delete:
 *     summary: 删除合同设置
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 合同设置ID
 *     responses:
 *       200:
 *         description: 删除成功
 *       404:
 *         description: 合同设置不存在
 *       500:
 *         description: 服务器内部错误
 */
router.delete("/delSettings", authenticateToken, async (req, res) => {
  try {
    const { id } = req.query;

    // 参数验证
    if (!id || isNaN(parseInt(id))) {
      return res.status(200).json({
        code: 201,
        message: "参数错误",
        error: "无效的合同设置ID",
      });
    }

    // 检查记录是否存在
    const [existingRows] = await db.query(
      "SELECT id, status FROM contract_settings WHERE id = ?",
      [parseInt(id)]
    );

    if (existingRows.length === 0) {
      return res.status(200).json({
        code: 201,
        message: "合同设置不存在",
        error: "指定的合同设置记录不存在",
      });
    }

    // 检查是否为激活状态
    if (existingRows[0].status === 1) {
      return res.status(200).json({
        code: 201,
        message: "操作失败",
        error: "激活状态的合同设置不能删除，请先停用后再删除",
      });
    }

    // 删除记录
    await db.query("DELETE FROM contract_settings WHERE id = ?", [
      parseInt(id),
    ]);

    res.json({
      code: 200,
      message: "删除成功",
      data: 1,
    });
  } catch (error) {
    console.error("删除合同设置失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development"
          ? error.message
          : "删除合同设置失败",
    });
  }
});

/**
 * @swagger
 * /api/contracts/updateSettings:
 *   put:
 *     summary: 编辑合同设置
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 合同设置ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - minAmount
 *               - maxAmount
 *               - feeAmount
 *               - feeType
 *               - percentage
 *               - status
 *             properties:
 *               minAmount:
 *                 type: number
 *                 example: 1000
 *               maxAmount:
 *                 type: number
 *                 example: 100000
 *               feeAmount:
 *                 type: number
 *                 example: 100
 *               feeType:
 *                 type: string
 *                 example: "fixed"
 *               percentage:
 *                 type: number
 *                 example: 0.05
 *               status:
 *                 type: integer
 *                 example: 1
 *               remark:
 *                 type: string
 *                 example: "合同设置备注"
 *     responses:
 *       200:
 *         description: 编辑成功
 *       400:
 *         description: 参数错误
 *       404:
 *         description: 合同设置不存在
 *       500:
 *         description: 服务器内部错误
 */
router.put("/updateSettings", authenticateToken, async (req, res) => {
  try {
    const {
      minAmount,
      maxAmount,
      feeAmount,
      feeType,
      percentage,
      status,
      remark = "",
      id,
    } = req.body;

    // 参数验证
    if (!id || isNaN(parseInt(id))) {
      return res.status(200).json({
        code: 201,
        message: "参数错误",
        error: "无效的合同设置ID",
      });
    }

    if (
      !minAmount ||
      !maxAmount ||
      !feeAmount ||
      !feeType ||
      percentage === undefined ||
      status === undefined
    ) {
      return res.status(200).json({
        code: 201,
        message: "参数不完整",
        error:
          "minAmount, maxAmount, feeAmount, feeType, percentage, status 为必填字段",
      });
    }

    if (minAmount >= maxAmount) {
      return res.status(200).json({
        code: 201,
        message: "参数错误",
        error: "最小金额必须小于最大金额",
      });
    }
    // 验证固定类型和比例类型只能开启一个
    if (feeType === "fixed" && (feeAmount <= 0 || percentage !== 0)) {
      return res.status(200).json({
        code: 201,
        message: "参数错误",
        error: "固定类型时，feeAmount必须大于0，percentage必须为0",
      });
    }
    // 验证已激活设置的金额区间不重叠，且相同金额区间只能开启一个
    if (status === 1) {
      const [allActive] = await db.query(
        "SELECT id, min_amount, max_amount, fee_type FROM contract_settings WHERE status = 1 AND id != ?",
        [parseInt(id)]
      );

      for (const existing of allActive) {
        // 检查是否存在相同的金额区间
        if (
          minAmount === existing.min_amount &&
          maxAmount === existing.max_amount
        ) {
          return res.status(200).json({
            code: 201,
            message: "参数错误",
            error: `相同金额区间只能开启一个，冲突区间：${existing.min_amount}-${existing.max_amount}（${existing.fee_type}类型）`,
          });
        }

        // 检查金额区间是否重叠
        if (
          (minAmount >= existing.min_amount &&
            minAmount < existing.max_amount) ||
          (maxAmount > existing.min_amount &&
            maxAmount <= existing.max_amount) ||
          (minAmount <= existing.min_amount && maxAmount >= existing.max_amount)
        ) {
          return res.status(200).json({
            code: 201,
            message: "参数错误",
            error: `金额区间与已激活的设置重叠，冲突区间：${existing.min_amount}-${existing.max_amount}（${existing.fee_type}类型）`,
          });
        }
      }
    }

    // 检查记录是否存在
    const [existingRows] = await db.query(
      "SELECT id FROM contract_settings WHERE id = ?",
      [parseInt(id)]
    );

    if (existingRows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: "合同设置不存在",
        error: "指定的合同设置记录不存在",
      });
    }

    // 更新记录
    await db.query(
      `UPDATE contract_settings 
       SET min_amount = ?, max_amount = ?, fee_amount = ?, fee_type = ?, 
           percentage = ?, status = ?, remark = ?, update_time = NOW() 
       WHERE id = ?`,
      [
        minAmount,
        maxAmount,
        feeAmount,
        feeType,
        percentage,
        status,
        remark,
        parseInt(id),
      ]
    );

    res.json({
      code: 200,
      message: "编辑成功",
      data: 1,
    });
  } catch (error) {
    console.error("编辑合同设置失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development"
          ? error.message
          : "编辑合同设置失败",
    });
  }
});

/**
 * @swagger
 * /api/contracts/settingsStatus:
 *   put:
 *     summary: 开启/关闭合同设置
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - id
 *               - status
 *             properties:
 *               id:
 *                 type: integer
 *                 description: 合同设置ID
 *                 example: 1
 *               status:
 *                 type: integer
 *                 enum: [0, 1]
 *                 description: 状态 0-关闭 1-开启
 *                 example: 1
 *     responses:
 *       200:
 *         description: 操作成功
 *       400:
 *         description: 参数错误
 *       404:
 *         description: 合同设置不存在
 *       500:
 *         description: 服务器内部错误
 */
router.put("/settingsStatus", authenticateToken, async (req, res) => {
  try {
    const { status, id } = req.body;

    // 参数验证
    if (!id || isNaN(parseInt(id))) {
      return res.status(200).json({
        code: 201,
        message: "参数错误",
        error: "无效的合同设置ID",
      });
    }

    if (status === undefined || (status !== 0 && status !== 1)) {
      return res.status(200).json({
        code: 201,
        message: "参数错误",
        error: "status必须为0或1",
      });
    }

    // 检查记录是否存在
    const [existingRows] = await db.query(
      "SELECT id, fee_type, status FROM contract_settings WHERE id = ?",
      [parseInt(id)]
    );

    if (existingRows.length === 0) {
      return res.status(200).json({
        code: 201,
        message: "合同设置不存在",
        error: "指定的合同设置记录不存在",
      });
    }

    const currentRecord = existingRows[0];

    // 如果要开启设置，需要检查同类型是否存在金额区间重叠
    if (status === 1) {
      // 获取当前记录的完整信息
      const [currentFullRecord] = await db.query(
        "SELECT min_amount, max_amount, fee_type FROM contract_settings WHERE id = ?",
        [parseInt(id)]
      );

      const currentMin = parseFloat(currentFullRecord[0].min_amount);
      const currentMax = parseFloat(currentFullRecord[0].max_amount);
      const currentFeeType = currentFullRecord[0].fee_type;

      // 检查所有已激活的设置是否存在金额区间重叠或相同（不限制费用类型）
      const [allActive] = await db.query(
        "SELECT id, min_amount, max_amount, fee_type FROM contract_settings WHERE status = 1 AND id != ?",
        [parseInt(id)]
      );

      for (const existing of allActive) {
        const existingMin = parseFloat(existing.min_amount);
        const existingMax = parseFloat(existing.max_amount);

        // 检查是否为相同金额区间
        if (currentMin === existingMin && currentMax === existingMax) {
          return res.status(200).json({
            code: 201,
            message: "参数错误",
            error: `相同金额区间只能开启一个，冲突区间：${existing.min_amount}-${existing.max_amount}（${existing.fee_type}类型），无法开启`,
          });
        }

        // 检查金额区间是否重叠
        // 两个区间重叠的条件：当前区间的最小值小于已有区间的最大值 且 当前区间的最大值大于已有区间的最小值
        if (currentMin < existingMax && currentMax > existingMin) {
          return res.status(200).json({
            code: 201,
            message: "参数错误",
            error: `已存在重叠的金额区间，冲突区间：${existing.min_amount}-${existing.max_amount}（${existing.fee_type}类型），无法开启`,
          });
        }
      }
    }

    // 更新当前记录状态
    await db.query(
      "UPDATE contract_settings SET status = ?, update_time = NOW() WHERE id = ?",
      [status, parseInt(id)]
    );

    res.json({
      code: 200,
      message: status === 1 ? "开启成功" : "关闭成功",
      data: 1,
    });
  } catch (error) {
    console.error("切换合同设置状态失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development"
          ? error.message
          : "切换合同设置状态失败",
    });
  }
});

/**
 * @swagger
 * /api/contracts/changeFiles:
 *   post:
 *     summary: 更新合同相关文件
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               existingFilePath:
 *                 type: string
 *                 description: 现有文件路径（相对于output目录的路径）
 *               templateName:
 *                 type: string
 *                 description: 模版文件名
 *               data:
 *                 type: object
 *                 description: 新的要填充的数据
 *               outputName:
 *                 type: string
 *                 description: 可选的新输出文件名
 *               contractId:
 *                 type: integer
 *                 description: 相关合同ID
 *     responses:
 *       200:
 *         description: 文件更新成功
 *       400:
 *         description: 请求参数错误
 *       404:
 *         description: 文件不存在
 *       500:
 *         description: 服务器内部错误
 */
router.post("/changeFiles", authenticateToken, async (req, res) => {
  try {
    const {
      lenderName,
      lenderIdCard,
      lenderPhone,
      borrowerRealName,
      borrowerType,
      borrowerPhone,
      borrowerRealIdCard,
      contractAmount,
      amountInWords,
      repaymentMethod,
      startDate,
      endDate,
      loanDays,
      annualRate,
      contractReason,
      additionalNotes,
      contractType,
      status,
      contractFile,
      contractNumber,
      id,
    } = req.body;
    const userId = req.user.id;

    // 验证必要参数
    if (!contractFile) {
      return res.status(400).json({
        code: 400,
        message: "缺少现有文件路径参数",
      });
    }

    // 如果提供了合同ID，验证该合同是否属于当前用户
    if (id) {
      const [contractRows] = await db.execute(
        "SELECT id FROM contracts WHERE id = ? AND user_id = ?",
        [id, userId]
      );

      if (contractRows.length === 0) {
        return res.status(403).json({
          code: 403,
          message: "无权访问此合同的文件",
        });
      }
    }

    // 获取完整的文件路径
    const filePath = path.join("/home/output/words", contractFile);
    console.log(filePath);
    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        code: 404,
        message: "文件不存在",
      });
    }

    // 确保输出目录存在
    const outputDir = path.dirname(filePath);
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }
    // 使用与/fileUpdate接口兼容的数据结构
    const contractData = {
      contractNumber: contractNumber || "",
      lenderName: lenderName || "",
      lenderIdCard: lenderIdCard || "",
      lenderPhone: lenderPhone || "",
      borrowerRealName: borrowerRealName || "",
      borrowerPhone: borrowerPhone || "",
      borrowerType: borrowerType || "个人",
      borrowerRealIdCard: borrowerRealIdCard || "",
      contractAmount: contractAmount || "0",
      amountInWords: amountInWords || "零元整",
      repaymentMethod: repaymentMethod || "一次性还本付息",
      startDate: startDate || new Date().toLocaleDateString("zh-CN"),
      endDate: endDate || new Date().toLocaleDateString("zh-CN"),
      loanDays: loanDays || "0",
      annualRate: annualRate || "0",
      contractReason: contractReason || "周转",
      additionalNotes: additionalNotes || "无",
      createdDate: new Date().toLocaleDateString("zh-CN"),
      createdTime: new Date().toLocaleTimeString("zh-CN"),
      // 添加合同ID，使其在文档中可访问
      contractId: id || "",
    };
    // 使用WordProcessor更新文档
    // 注意：应该使用固定的模板文件，而不是输出文件路径作为模板
    const templatePath = path.join(__dirname, "../", "模版.docx");
    const result = await WordProcessor.processTemplate(
      templatePath,
      contractData,
      filePath
    );

    if (result.success) {
      res.json({
        code: 200,
        message: "文件更新成功",
      });
    } else {
      res.status(500).json({
        code: 500,
        message: result.message || "文件更新失败",
      });
    }
  } catch (error) {
    console.error("更新合同文件时出错:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development"
          ? error.message
          : "更新合同文件失败",
    });
  }
});

// 新增一个软删除合同的接口
/**
 * @swagger
 * /api/contracts/delete/{id}:
 *   delete:
 *     summary: 软删除合同（将状态设置为-1）
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 合同ID
 *     responses:
 *       200:
 *         description: 合同删除成功
 *       400:
 *         description: 请求参数错误
 *       403:
 *         description: 无权删除此合同
 *       404:
 *         description: 合同不存在
 *       500:
 *         description: 服务器内部错误
 */
router.delete("/delete/:id", authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 验证合同ID格式
    if (!id || isNaN(parseInt(id))) {
      return res.status(200).json({
        code: 400,
        message: "无效的合同ID",
      });
    }

    const contractId = parseInt(id);

    // 检查合同是否存在，并验证是否属于当前用户
    const [contractRows] = await db.execute(
      "SELECT id FROM contracts WHERE id = ? AND user_id = ? AND status != -1",
      [contractId, userId]
    );

    if (contractRows.length === 0) {
      // 检查合同是否存在（不检查所有权），用于返回不同的错误消息
      const [checkRows] = await db.execute(
        "SELECT id, status FROM contracts WHERE id = ?",
        [contractId]
      );

      if (checkRows.length === 0) {
        return res.status(200).json({
          code: 400,
          message: "合同不存在",
        });
      } else if (checkRows[0].status === -1) {
        return res.status(200).json({
          code: 400,
          message: "合同已被删除",
        });
      } else {
        return res.status(200).json({
          code: 400,
          message: "无权限删除此合同",
        });
      }
    }

    // 获取数据库连接并处理事务
    const connection = await db.getConnection();

    try {
      // 开始事务
      await connection.beginTransaction();

      // 软删除：将合同状态设置为-1
      await connection.execute(
        "UPDATE contracts SET status = -1, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
        [contractId]
      );

      // 提交事务
      await connection.commit();
      res.status(200).json({
        code: 200,
        message: "合同删除成功",
      });
    } catch (error) {
      // 回滚事务
      await connection.rollback();
      throw error;
    } finally {
      // 释放连接
      connection.release();
    }
  } catch (error) {
    console.error("删除合同失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development" ? error.message : "删除合同失败",
    });
  }
});

/**
 * @swagger
 * /api/contracts/updateStatus/{id}:
 *   put:
 *     summary: 修改合同状态
 *     tags: [Contracts]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 合同ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - status
 *             properties:
 *               status:
 *                 type: integer
 *                 enum: [1, 2, 3, 4, 5, 6]
 *                 description: 合同状态（1-待生效，2-生效中，3-已完成，4-已违约，5-新状态1，6-新状态2）
 *                 example: 2
 *     responses:
 *       200:
 *         description: 更新成功
 *       400:
 *         description: 参数错误
 *       404:
 *         description: 合同不存在
 *       403:
 *         description: 无权限修改此合同
 *       500:
 *         description: 服务器内部错误
 */
router.put("/updateStatus/:id", authenticateToken, async (req, res) => {
  try {
    const contractId = parseInt(req.params.id);
    const { status } = req.body;
    const userId = req.user.id;

    // 参数验证
    if (isNaN(contractId)) {
      return res.status(200).json({
        code: 400,
        message: "参数错误",
        error: "无效的合同ID",
      });
    }

    if (!status) {
      return res.status(200).json({
        code: 400,
        message: "参数错误",
        error: "status字段不能为空",
      });
    }

    // 检查合同是否存在，并获取完整信息（包括lender_name）
    const [contractRows] = await db.execute(
      "SELECT id, user_id, lender_name FROM contracts WHERE id = ?",
      [contractId]
    );

    if (contractRows.length === 0) {
      return res.status(200).json({
        code: 404,
        message: "合同不存在",
        error: "未找到指定ID的合同",
      });
    }

    // 获取当前用户的详细信息，用于验证是否为出借人
    const [userRows] = await db.execute(
      "SELECT id, realName FROM user WHERE id = ?",
      [userId]
    );
    const currentUser = userRows[0];

    // 检查用户是否出借人或合同创建者
    const contract = contractRows[0];
    const isCreator = contract.user_id === userId;
    const isLender =
      currentUser &&
      currentUser.realName &&
      contract.lender_name &&
      currentUser.realName === contract.lender_name;

    if (!isCreator && !isLender) {
      return res.status(200).json({
        code: 400,
        message: "无权限",
        error: "您无权修改此合同",
      });
    }

    // 更新合同状态
    await db.execute("UPDATE contracts SET status = ? WHERE id = ?", [
      status,
      contractId,
    ]);

    // 返回成功响应
    res.json({
      code: 200,
      message: "更新成功",
      data: {
        contractId: contractId,
        newStatus: status,
      },
    });
  } catch (error) {
    console.error("修改合同状态失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development"
          ? error.message
          : "修改合同状态失败",
    });
  }
});

// 新增一个展期的接口， 修改合同状态为6 新增展期字段 extend_end_date 支付状态pay_status为 2  支付金额pay_amount 修改为9.9
/**
 * @swagger
 * /contracts/extend/{id}:
 *   put:
 *     summary: 合同展期接口
 *     description: 修改合同状态为6，设置展期截止日期，将支付状态置为待支付(2)
 *     tags:
 *       - 合同管理
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 合同ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - extendEndDate
 *             properties:
 *               extendEndDate:
 *                 type: string
 *                 format: date
 *                 description: 展期截止日期
 *                 example: "2025-12-31"
 *     responses:
 *       200:
 *         description: 展期成功
 *       400:
 *         description: 参数错误
 *       404:
 *         description: 合同不存在
 *       403:
 *         description: 无权限操作此合同
 *       500:
 *         description: 服务器内部错误
 */
router.put("/extend/:id", authenticateToken, async (req, res) => {
  try {
    const contractId = parseInt(req.params.id);
    const { extendEndDate } = req.body;
    const userId = req.user.id;

    // 参数验证
    if (isNaN(contractId)) {
      return res.status(200).json({
        code: 400,
        message: "参数错误",
        error: "无效的合同ID",
      });
    }

    if (!extendEndDate) {
      return res.status(200).json({
        code: 400,
        message: "参数错误",
        error: "extendEndDate字段不能为空",
      });
    }

    // 验证日期格式
    const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
    if (!dateRegex.test(extendEndDate)) {
      return res.status(200).json({
        code: 400,
        message: "参数错误",
        error: "日期格式不正确，请使用YYYY-MM-DD格式",
      });
    }

    // 检查合同是否存在，并获取完整信息（包括lender_name）
    const [contractRows] = await db.execute(
      "SELECT id, user_id, lender_name, end_date, status, extend_end_date, pay_status FROM contracts WHERE id = ?",
      [contractId]
    );

    if (contractRows.length === 0) {
      return res.status(200).json({
        code: 404,
        message: "合同不存在",
        error: "未找到指定ID的合同",
      });
    }

    // 获取当前用户的详细信息，用于验证是否为出借人
    const [userRows] = await db.execute(
      "SELECT id, realName FROM user WHERE id = ?",
      [userId]
    );
    const currentUser = userRows[0];

    // 检查用户是否出借人或合同创建者
    const contract = contractRows[0];
    const isCreator = contract.user_id === userId;
    const isLender =
      currentUser &&
      currentUser.realName &&
      contract.lender_name &&
      currentUser.realName === contract.lender_name;

    if (!isCreator && !isLender) {
      return res.status(200).json({
        code: 403,
        message: "无权限",
        error: "您无权对此合同进行展期操作",
      });
    }

    // 检查合同当前状态是否可以展期（通常只有生效中的合同可以展期）
    if (contract.status !== 2) {
      return res.status(200).json({
        code: 400,
        message: "操作失败",
        error: "只有生效中的合同才能进行展期操作",
      });
    }

    // 更新合同状态为6（展期）、设置展期截止日期、支付状态为2（待支付）
    await db.execute(
      "UPDATE contracts SET status = 6, extend_end_date = ?, pay_status = 2, pay_amount = 9.9 WHERE id = ?",
      [extendEndDate, contractId]
    );
    res.status(200).json({
      code: 200,
      message: "操作成功",
      data: {
        contractId: contractId,
        extendEndDate: extendEndDate,
        newStatus: 6,
        payStatus: 2,
      },
    });
  } catch (error) {
    console.error("合同展期失败:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development" ? error.message : "合同展期失败",
    });
  }
});

module.exports = router;
